var wineApp = wineApp || {};
wineApp.biz = wineApp.biz || {};
//TODO:系统启动的时候，需要根据本地数据库的信息校验登录信息，并回写login_flag标志位checked
wineApp.biz.common = (function() {
    var API_URL = wineApp.CONFIG.API;
    var userName = null;
    var password = null;
    var param = $.url().param();
    var path = wineApp.common.isRootPath() ? "" : "../"
    var url = param["refURL"] == null ? "index.html" : param["refURL"];
    url = path + url;
    var login = function(username, pwd, successCallback, failCallback) {

        //var key = params["key"] == null ? "" : params["key"];
        var token = wineApp.ajax.getCert();
        console.log("pwd:" + pwd);
        var epwd = CryptoJS.MD5(token + CryptoJS.MD5(pwd).toString());
        var params = {
            phone: username,
            epwd: pwd
        }
        password = pwd;
        userName = username;
        var successFn = onSuccess;
        var failFn = onFail;
        if ($.isFunction(successCallback)) {
            successFn = successCallback;
        }
        if ($.isFunction(failCallback)) {
            failFn = failCallback;
        }
        wineApp.ajax.post(API_URL.login, params)
            .done(successFn)
            .fail(function() {
                wineApp.tool.toastError('账号或密码错误');
            });
    }

    function onSuccess(data) {
        saveToStorage(true, data);
        wineApp.biz.common.saveToStorage(true, data);
        //window.location.href = url;
        window.location.href = 'index.html';
    }

    function saveToStorage(flag, data) {

        var key = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'userInfo';
        var key_loginName = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'username';
        var key_pwd = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'password';
        var key_login_flag = wineApp.CONFIG.STORAGE.PREFIX + '.' + 'login_flag';
        if (flag) {
            wineApp.localStorage.set(key_loginName, userName);
            wineApp.localStorage.set(key_pwd, password);
            wineApp.localStorage.set(key_login_flag, "checked");
            wineApp.localStorage.set('wineApp.lastest_refer', null);
            wineApp.localStorage.set(key, data.user);

        } else {
            wineApp.localStorage.set(key, null);
            wineApp.localStorage.set(key_login_flag, "unchecked");
        }
    }

    function onFail(data) {
        console.log(data);
        wineApp.tool.toastError('登录出错误了');
        wineApp.biz.common.saveToStorage(false, null);
    }

    return {
        login: login,
        saveToStorage: saveToStorage
    }
})();